var prefix = "/jzweb/trackDraw";
var isDrawing = null; // 标记是否正在进行抽签

let falg = false;
var timerId
var types = null
var paging = 1,pagingsize=15
$(function() {
    load();
});

$(document).ready(function() {
    lottery()
});

function load() {
    paging =1
    pagingsize= 10000
    $('#exampleTable')
        .bootstrapTable(
            {
                method : 'get', // 服务器数据的请求方式 get or post
                url : `/jzweb/trackDraw/getTrack?current=${paging}&size=${pagingsize}`, // 服务器数据的加载地址
                //	showRefresh : true,
                //	showToggle : true,
                //	showColumns : true,
                iconSize : 'outline',
                toolbar : '#exampleToolbar',
                theadClasses: "thead-dark",
                striped : true, // 设置为true会有隔行变色效果
                dataType : "json", // 服务器返回的数据类型
                pagination : false, // 设置为true会在底部显示分页条
                singleSelect : false, // 设置为true将禁止多选
                //search : true, // 是否显示搜索框
                showColumns : false, // 是否显示内容下拉框（选择显示的列）
                sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者 "server"
                queryParamsType : "",
                responseHandler : function(res){
                    if(res.code !== '0') {
                        layer.msg(res.msg);
                        return false
                    }
                    let myData=[]
                    for (let i = 0; i < res.data.records.length; i++) {
                        let item=res.data.records[i]
                        for (let j = 0; j < item.comRealityDOS.length; j++) {
                            item['name'+(j+1)]=item.comRealityDOS[j].name
                            item['field'+(j+1)]=item.comRealityDOS[j].field
                            item.recordNumber=item.comRealityDOS[j].recordNumber
                        }
                        myData.push(item)
                    }
                    console.log('myDatamyDatamyData',res.data,myData)
                    return {
                        "rows": myData, //数据
                        "total": res.data.total,//总数
                    };
                },
                columns : [
                    {
                        field : 'unitName',
                        title : '参赛院校',
                        align : 'center',
                        valign:'middle'
                    },
                    {
                        field : 'recordNumber',
                        title : '检录序号',
                        class : 'recordNumber',
                        align : 'center',
                        valign:'middle',
                        formatter : function(value, row, index) {
                            isDrawing=null!=value&&''!=value
                            if(isDrawing) {
                                return  value
                            }
                            return '-'
                        }
                    },
                    {
                        field : 'name1',
                        title : '姓名',
                        align : 'center',
                        valign:'middle'
                    },
                    {
                        field : 'field1',
                        title : '赛场',
                        class : 'field1',
                        align : 'center',
                        valign:'middle',
                        formatter : function(value, row, index) {
                            isDrawing=null!=value&&''!=value
                            if(isDrawing) {
                                return  value=='B1'?'B':value=='B2'?'C':'D'
                            }
                            return '-'
                        }
                    },
                    {
                        field : 'name2',
                        title : '姓名',
                        align : 'center',
                        valign:'middle'
                    },
                    {
                        field : 'field2',
                        title : '赛场',
                        class : 'field2',
                        align : 'center',
                        valign:'middle',
                        formatter : function(value, row, index) {
                            if(isDrawing) {
                                return value=='B1'?'B':value=='B2'?'C':'D'
                            }
                            return '-'
                        }
                    },
                    {
                        field : 'name3',
                        title : '姓名',
                        align : 'center',
                        valign:'middle'
                    },
                    {
                        field : 'field3',
                        title : '赛场',
                        class : 'field3',
                        align : 'center',
                        valign:'middle',
                        formatter : function(value, row, index) {
                            if(isDrawing) {
                                return  value=='B1'?'B':value=='B2'?'C':'D'
                            }
                            return '-'
                        }
                    },
                ],
                onLoadSuccess: function(data) {
                        setTrBackground()
                }
            });
}
let timerId1;
window.onresize=()=>{
    clearTimeout(timerId1);
    timerId1 = setTimeout(() => {
       setTrBackground()
    }, 200);
}
function setTrBackground(outnumber=1,color=['#fff','rgb(239 239 239)']){
    // 在这里添加你想要执行的代码，例如更新其他元素或执行其他处理
    let mytr =$("tbody>tr")
    console.log('mytr',mytr.length)
    //获取可视区域大小
    let myTableLoadingrHeight=$(".fixed-table-loading")[0].scrollHeight,
        mythead=$("thead")[0].scrollHeight,
        mytrHeight=mytr.length>0?mytr[0].scrollHeight:0

    console.log('==myTableLoadingrHeight=',myTableLoadingrHeight)
    console.log('==mythead=',mythead)
    console.log('==mytrHeight=',mytrHeight)
    // myTableLoadingrHeight=myTableLoadingrHeight-mythead
    //一页显示几个
    let number =parseInt(myTableLoadingrHeight/mytrHeight),index=0;
    number=number-outnumber

    let numbers=number
    //设置颜色
    for (let i = 0; i < mytr.length; i++) {
        if(i>numbers){
            index=index==1?0:1
            numbers=numbers+number
        }
        mytr[i].style.backgroundColor=color[index]
    }
}
function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

//导出
function downExcelModelFile() {
    layer.confirm('您确定要导出吗？', {
        btn1:function(index){
            if(!isDrawing) {
                layer.msg('请先完成抽签')
                layer.close(index);
                return
            }
            try {
                window.location.href = `/jzweb/trackDraw/downloadImportTrackDraw?current=1&size=10000`;
                layer.close(index)
            }catch (e) {
                layer.msg('导出失败')
            }

        }
    });


}
function myClear(){
    layer.confirm('您确定要清除吗？', {
        btn1:function(index){
            $.ajax({
                type : "get",
                url : `/jzweb/trackDraw/clearDraw`,
                async : false,
                error : function(request) {
                    parent.layer.alert(request);
                },
                success : function(res) {
                    if (res.code === '0') {
                        layer.msg('清除完毕')
                        reLoad()
                    } else {
                        parent.layer.alert(res.msg)
                    }

                }
            });
        }
    });

}

function trackDrawCreate() {
    $.ajax({
        type : "get",
        url : `/jzweb/trackDraw/trackDraw?current=${paging}&size=${pagingsize}`,
        async : false,
        error : function(request) {
            parent.layer.alert(request);
        },
        success : function(res) {
            if (res.code === '0') {
                layer.msg('抽签完毕')
                reLoad()
            } else {
                parent.layer.alert(res.msg)
            }

        }
    });
}

// 抽签
function lottery() {


    // B随机抽签
    $('#drawBButton').click(function() {
        if(falg) {
            return layer.msg('抽签中')
        }
        if(isDrawing){
            return layer.msg('抽签已完成')
        }
        let index = layer.confirm('确定开始抽签？', {
            btn: ['确定', '取消']
        }, function () {
            timerId = setInterval(updateBNumbers, 100);
            types = 1
            isDrawing = true
            falg = true
            layer.close(index);
            // // 点击停止按钮结束抽签
        })

    });

    $('#stopButton').click(async function() {
        if(falg) {
        let index = layer.confirm('确定停止抽签？', {
            btn: ['确定', '取消']
        }, function () {
            if(isDrawing) {

                    clearInterval(timerId);
                    trackDrawCreate()


            }
            falg = false
            layer.close(index);
        })
        }else {
            layer.msg('抽签已完成')
        }
    });
}

// 更新序号
function updateBNumbers() {
    let rows = $('#exampleTable').bootstrapTable('getData'); // 获取表格数据
    let total = rows.length * 1
    if (rows.length === 0)  return layer.msg('暂无选手信息')
    var tableRows = $('#exampleTable tbody tr');
    var oldtotal=[]
    tableRows.each(function(index, row) {
        var randomNumber = getRandomNumber(1, total,oldtotal);
        $(row).find('.recordNumber').text(randomNumber);
        //三个赛场循环
        var oldfield=[],bb=getRandomNumber(1, 3,oldfield)
        $(row).find('.field1').text(bb==1?'B':bb==2?'C':'D');
        bb=getRandomNumber(1, 3,oldfield)
        $(row).find('.field2').text(bb==1?'B':bb==2?'C':'D');
        bb=getRandomNumber(1, 3,oldfield)
        $(row).find('.field3').text(bb==1?'B':bb==2?'C':'D');

    });
}

// 生成指定范围的随机数
function getRandomNumber(min, max,list) {
    let randomNumber;
    do {
        randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; // 生成1到5之间的随机整数
    } while (list.includes(randomNumber));
    list.push(randomNumber)
    return randomNumber;

}